package CaixaEletronico;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


import com.mysql.jdbc.PreparedStatement;

public class ContaDao {
	private Connection connection;

	  public ContaDao() {
	    this.connection = new ConnectionFactory().getConnection();
	  }
	  
	  public boolean insert(Conta conta,Cliente cliente) throws SQLException {
		     String sql = "insert into tb_conta" +
		             "(SALDO,ID,LIMITE_EMPRESTIMO)" +
		             " values (?,?,?);";
		            
		     try {
		         
		         PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
		         
		         
		         stmt.setDouble(1,conta.getSaldo());
		         stmt.setInt(2,conta.getId());
		         stmt.setDouble(3,cliente.getSalario()*3);
		      
		         
		         stmt.execute();
		         stmt.close();
		             
		     } catch (SQLException e) {
		         throw new RuntimeException(e);
		     }
		     return true;
		 }


	public double getSaldo(int id) throws SQLException {
		PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement("select SALDO from tb_conta  where ID = "+id);
			
			
		ResultSet rs = stmt.executeQuery();
		
		double saldo = 0.0;
			
		if(rs.next()){
				saldo = rs.getDouble("SALDO");
			}
			
		stmt.close();
			
		rs.close();
		
		return saldo;
	}
	
	public void Deposita(int id,double valor) throws SQLException{
		PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement("UPDATE tb_conta  SET SALDO  = SALDO + "+valor+"WHERE ID = "+id);
		
		int rs = stmt.executeUpdate();
		
		stmt.close();
	}


	public void Saque(int id,double saque) throws SQLException {
		PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement("UPDATE tb_conta  SET SALDO  = SALDO - "+saque+"WHERE ID = "+id);
			
			int rs = stmt.executeUpdate();
			
			stmt.close();
		
	}
	public void AtualizarLimiteEmprestimo(int id,double valor) throws SQLException {
		PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement("UPDATE tb_conta SET LIMITE_EMPRESTIMO  = LIMITE_EMPRESTIMO - "+valor+"WHERE ID = "+id);
			
			int rs = stmt.executeUpdate();
			
			stmt.close();
		
	}
	
	public double LimiteEmprestimo(int id) throws SQLException{
		PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement("Select  LIMITE_EMPRESTIMO from tb_conta WHERE ID = "+id);
		  
		ResultSet rs = stmt.executeQuery();
		
		rs.next();
			 
		double valor = rs.getInt("LIMITE_EMPRESTIMO");
		
		rs.close();
		stmt.close();
		
		return valor;
	}
	

	public void disconnect() throws SQLException {
		this.connection.close();
		
	}


	  
}

